package com.xywl.escort.view.farm

import android.graphics.Color
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.content.ContextCompat
import android.text.Spannable
import android.text.SpannableString
import android.text.SpannableStringBuilder
import android.text.TextUtils
import android.text.style.AbsoluteSizeSpan
import android.text.style.ForegroundColorSpan
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.trello.rxlifecycle2.LifecycleTransformer
import com.xywl.escort.R
import com.xywl.escort.adapter.LeaderBoardAdapter
import com.xywl.escort.base.BaseActivity
import com.xywl.escort.bean.PreBuyResp
import com.xywl.escort.bean.ProjectDetailResp
import com.xywl.escort.bean.RankingListResp
import com.xywl.escort.common.PreferenceKeys.TOKEN
import com.xywl.escort.utils.NetworkUtil
import com.xywl.escort.utils.NumberFormatUtils
import com.xywl.escort.utils.RxSPTool
import com.xywl.escort.utils.ToastUtil
import com.xywl.escort.view.farm.rank.SubscribeRankFragment
import dagger.android.AndroidInjection
import dagger.android.AndroidInjector
import dagger.android.DispatchingAndroidInjector
import dagger.android.support.HasSupportFragmentInjector
import kotlinx.android.synthetic.main.activity_project_detail.*
import timber.log.Timber
import java.math.BigDecimal
import java.util.*
import javax.inject.Inject

/**
 * 项目详情
 */
@Route(path = "/xy/project/detail")
class ProjectDetailActivity : BaseActivity(), ProjectDetailContract.View, HasSupportFragmentInjector {

    private lateinit var mAdapter: LeaderBoardAdapter
    private val mDataBeanList = ArrayList<RankingListResp.DataBean.ListBean>()

    @Inject
    lateinit var mPresenter: ProjectDetailContract.Presenter

    @Autowired
    @JvmField
    var projectId: String = ""

    @Autowired
    @JvmField
    var title: String = ""

    private var buybackCompanyId: String = ""

    @Inject
    lateinit var supportFragmentInjector: DispatchingAndroidInjector<Fragment>

    private var isCheck: Boolean = true

    private var mDataBean: ProjectDetailResp.DataBean? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        AndroidInjection.inject(this)
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_project_detail)
        ARouter.getInstance().inject(this)
        showBackButton()
        setTitleText(title)

//        val view = findViewById<View>(R.id.root_container_layout)
//        if (null != view) {
//            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//                ViewCompat.setOnApplyWindowInsetsListener(view) { _, insets -> insets.consumeSystemWindowInsets() }
//            }
//        }
        initView()
        setListener()
    }

    override fun supportFragmentInjector(): AndroidInjector<Fragment> {
        return supportFragmentInjector
    }

    override fun onResume() {
        super.onResume()
        initData()
    }

    private fun initView() {
//        img_btn_title_right.visibility = View.VISIBLE
//        img_btn_title_right.setImageResource(R.mipmap.order_record)

        mAdapter = LeaderBoardAdapter(R.layout.item_leader_board, mDataBeanList)

        val colorSpan = ForegroundColorSpan(Color.parseColor("#00CBA6"))

        val detailRepurchase = getString(R.string.order_detail_repurchase)
        val repurchaseStyle = SpannableStringBuilder(detailRepurchase)
        repurchaseStyle.setSpan(colorSpan, 2, detailRepurchase.length, Spannable.SPAN_EXCLUSIVE_INCLUSIVE)
        text_repurchase_detail.text = repurchaseStyle

        val orderProtection = getString(R.string.order_protection)
        val protectionStyle = SpannableStringBuilder(orderProtection)
        protectionStyle.setSpan(colorSpan, 2, orderProtection.length, Spannable.SPAN_EXCLUSIVE_INCLUSIVE)
        text_protection.text = protectionStyle

        val projectFragment = ProjectDescriptionFragment.newInstance("http://statich5.nmbjvip.com/projectDetails.html?id=$projectId")
        val transferFragment = ProjectDescriptionFragment.newInstance("http://statich5.nmbjvip.com/projectDescription.html?id=$projectId")
        val subscribeRankFragment = SubscribeRankFragment.newInstance(projectId)
        val tabNames = arrayOf("项目描述", "产品描述", "认购排行榜")
        val fragments = arrayOf(projectFragment, transferFragment, subscribeRankFragment)
        val adapter = ProjectPagerAdapter(supportFragmentManager, tabNames, fragments)
        tabLayout.setupWithViewPager(viewPager)
        viewPager.adapter = adapter
        viewPager.offscreenPageLimit = tabNames.size
        viewPager.currentItem = 0
    }

    private fun initData() {
        mPresenter.takeView(this)
        mPresenter.loadProjectDetail(projectId)
    }

    private fun setListener() {
//        img_btn_title_right.setOnClickListener {
//            ARouter.getInstance()
//                    .build("/xy/operation/record")
//                    .withString("projectId", projectId)
//                    .navigation()
//        }

        text_agreement.setOnClickListener {
            ARouter.getInstance().build("/xy/web/links")
                    .withString("title", getString(R.string.tips_service_agreement))
                    .withString("url", "file:///android_asset/service_agreement.html")
                    .navigation()
        }

        checkbox.setOnCheckedChangeListener { _, isChecked ->
            isCheck = isChecked
        }

        btn_subscribe.setOnClickListener {
            subscribe()
        }

        text_repurchase_detail.setOnClickListener {
            if (!TextUtils.isEmpty(buybackCompanyId)) {
                ARouter.getInstance().build("/xy/web/links")
                        .withString("url", "http://statich5.nmbjvip.com/businessDetails.html?id=$buybackCompanyId&&projectId=$projectId")
                        .withString("title", "企业详情").navigation()
            } else {
                ToastUtil.showTip(this, "企业信息错误，请联系客服")
            }
        }

        text_protection.setOnClickListener {
            if (!TextUtils.isEmpty(buybackCompanyId)) {
                ARouter.getInstance().build("/xy/web/links")
                        .withString("url", "http://statich5.nmbjvip.com/guarantee.html?id=$buybackCompanyId&&projectId=$projectId")
                        .withString("title", "收购保障").navigation()
            } else {
                ToastUtil.showTip(this, "企业信息错误，请联系客服")
            }
        }

        btn_status.setOnClickListener {
            ARouter.getInstance().build("/xy/login").navigation()
        }
    }

    private fun subscribe() {
        if (!NetworkUtil.isAvailable(this)) {
            ToastUtil.showTip(this, R.string.network_error)
            return
        }
        val token = RxSPTool.getString(this, TOKEN)
        if (!TextUtils.isEmpty(token)) {
            if (isCheck) {
                val numStr = edit_buy_num.text.toString().trim()
                if (!TextUtils.isEmpty(numStr)) {
                    val num = Integer.valueOf(numStr)
                    mPresenter.preBuy(projectId, 1, num)
                } else {
                    ToastUtil.showTip(this, "请输入认购份数")
                }
            } else {
                ToastUtil.showTip(this, "请先同意服务协议")
            }
        } else {
            ToastUtil.showTip(this, "用户未登录")
            ARouter.getInstance().build("/xy/login").navigation()
        }
    }

    override fun isActive(): Boolean {
        return false
    }

    override fun <T : Any?> bindToLife(): LifecycleTransformer<T> {
        return this.bindToLifecycle()
    }

    override fun loadProjectDetailSuccess(dataBean: ProjectDetailResp.DataBean?) {
        Timber.tag("loadProjectDetailSuccess").e("dataBean=$dataBean")
        layout_bottom_tools.visibility = View.VISIBLE
        layout_project_content.visibility = View.VISIBLE
        progress_bar.visibility = View.GONE

        mDataBean = dataBean

        if (!TextUtils.isEmpty(dataBean!!.buybackCompanyId)) {
            buybackCompanyId = dataBean.buybackCompanyId
        }
        if (null != dataBean.marketPriceYuan) {
            val marketPriceYuan = NumberFormatUtils.getInstance().format(dataBean.marketPriceYuan.toDouble())
            val marketPrice = "约${marketPriceYuan}元"
            val spanString = SpannableString(marketPrice)
            val absoluteSizeSpan = AbsoluteSizeSpan(14, true)
            spanString.setSpan(absoluteSizeSpan, marketPrice.lastIndexOf("约"), marketPrice.lastIndexOf("约") + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
            val absoluteSizeSpan1 = AbsoluteSizeSpan(14, true)
            spanString.setSpan(absoluteSizeSpan1, marketPrice.lastIndexOf("元"), marketPrice.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
            text_market_price_value.text = spanString
        }
        if (null != dataBean.subscribePriceYuan) {
            val subscribePriceYuan = NumberFormatUtils.getInstance().format(dataBean.subscribePriceYuan.toDouble())
            text_subscription_price_value.text = subscribePriceYuan + "元"
        }
        if (null != dataBean.buybackPriceYuan) {
            val buybackPriceYuan = NumberFormatUtils.getInstance().format(dataBean.buybackPriceYuan.toDouble())
            text_consignment_price_value.text = buybackPriceYuan + "元"
        }
        if (null != dataBean.subscribeTotalPriceYuan) {
            val subscribeTotalPriceYuan = NumberFormatUtils.getInstance().format(dataBean.subscribeTotalPriceYuan.toDouble())
            text_total_amount.text = subscribeTotalPriceYuan
        }
        text_cycle.text = "" + dataBean.borrowCycle + "天"
        if (!TextUtils.isEmpty(dataBean.buybackCompanyName)) {
            val company = "收购企业：" + dataBean.buybackCompanyName
            // text_repurchase_company.text = "收购企业：" + dataBean.buybackCompanyName
            val spanString = SpannableString(company)
            val absoluteSizeSpan = AbsoluteSizeSpan(16, true)
            spanString.setSpan(absoluteSizeSpan, company.lastIndexOf("业：") + 1, company.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
            val span = ForegroundColorSpan(ContextCompat.getColor(this, R.color.main_body_major_color))
            spanString.setSpan(span, company.lastIndexOf("业：") + 1, company.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
            text_repurchase_company.text = spanString
        }

        text_subscription_num.text = "" + dataBean.subscribeNum
        text_project_remaining.text = "项目剩余" + dataBean.available + "份"
        val progress = dataBean.subscribeRate.toInt()
        progressBar.progress = progress
        val token = RxSPTool.getString(this, TOKEN)
        if (TextUtils.isEmpty(token)) {
            layout_project_option.visibility = View.GONE
            btn_status.visibility = View.VISIBLE
            btn_status.text = "立即登录"
            btn_status.setTextColor(ContextCompat.getColor(this, android.R.color.white))
            btn_status.setBackgroundColor(ContextCompat.getColor(this, R.color.normal_text_color))
            btn_status.isEnabled = true
        } else {
            // 项目状态： 1-认购中 2-已售罄 3-派单中 4-待认购 5-成长中 6-分红结束 7-项目失败 -1-未知
            when (dataBean.projectStatus) {
                1 -> {
                    layout_project_option.visibility = View.VISIBLE
                    btn_status.visibility = View.GONE
                    btn_subscribe.text = "认购"
                    btn_subscribe.isEnabled = true
                    btn_subscribe.setTextColor(ContextCompat.getColor(this, android.R.color.white))
                    btn_subscribe.setBackgroundColor(ContextCompat.getColor(this, R.color.normal_text_color))
                }
                2 -> {
                    layout_project_option.visibility = View.VISIBLE
                    btn_status.visibility = View.GONE
                    btn_subscribe.text = "抢光了"
                    btn_subscribe.isEnabled = false
                    btn_subscribe.setTextColor(ContextCompat.getColor(this, R.color.main_body_prompt_color))
                    btn_subscribe.setBackgroundColor(ContextCompat.getColor(this, R.color.enable_background))
                }
                3 -> {
                    layout_project_option.visibility = View.GONE
                    btn_status.visibility = View.VISIBLE
                    btn_status.text = "派单中"
                    btn_status.setBackgroundColor(ContextCompat.getColor(this, R.color.enable_background))
                    btn_status.isEnabled = false
                }
                4 -> {
                    layout_project_option.visibility = View.GONE
                    btn_status.visibility = View.VISIBLE
                    btn_status.text = "即将开放认购"
                    btn_status.setBackgroundColor(ContextCompat.getColor(this, R.color.enable_background))
                    btn_status.isEnabled = false
                }
                5 -> {
                    layout_project_option.visibility = View.GONE
                    btn_status.visibility = View.VISIBLE
                    btn_status.text = "成长中"
                    btn_status.setBackgroundColor(ContextCompat.getColor(this, R.color.enable_background))
                    btn_status.isEnabled = false
                }
                6 -> {
                    layout_project_option.visibility = View.GONE
                    btn_status.visibility = View.VISIBLE
                    btn_status.text = "分红结束"
                    btn_status.setBackgroundColor(ContextCompat.getColor(this, R.color.enable_background))
                    btn_status.isEnabled = false
                }
                7 -> {
                    layout_project_option.visibility = View.GONE
                    btn_status.visibility = View.VISIBLE
                    btn_status.text = "项目失败"
                    btn_status.setBackgroundColor(ContextCompat.getColor(this, R.color.enable_background))
                    btn_status.isEnabled = false
                }
                else -> {
                }
            }
        }
    }

    override fun loadProjectDetailFailure() {
        Timber.e("loadProjectDetailSuccess")
        layout_bottom_tools.visibility = View.VISIBLE
        layout_project_content.visibility = View.VISIBLE
        progress_bar.visibility = View.GONE
    }

    override fun preBuySuccess(resp: PreBuyResp?) {
        val numStr = edit_buy_num.text.toString().trim()
        if (!TextUtils.isEmpty(numStr)) {
            val num = BigDecimal(numStr)
            val payMoney = num.multiply(mDataBean!!.subscribePriceYuan)
            val condMinDay = mDataBean!!.borrowCycle
            ARouter.getInstance()
                    .build("/xy/project/pay/dialog")
                    .withInt("condMinDay", condMinDay)
                    .withString("numStr", numStr)
                    .withString("projectId", projectId)
                    .withObject("payMoney", payMoney)
                    .navigation()
        } else {
            Timber.e("preBuySuccess numStr = null")
        }
    }

    override fun preBuyFailure(msg: String) {
        ToastUtil.showTip(this, msg)
        Timber.e("preBuyFailure")
    }
}
